<?php

/**
 * 制作:  叶风
 * Qq:    355007778
 * Email: ye.fn@163.com
 * 
 */

class YF_f
{
    /**
     * @var array 全局变量
     */
	static $arr = array('debug_info'=>array()  //大于0时记录
					);
    
    /**
     * @var array 配置值
     */
    static $config = array();
    /**
     * 显示错误
     * $debug  0关闭, >=1一般, >=2 Sql, >=2中断
     * @param type $str 错误内容
     * @param type $b  错误级别: 0系统级错误,其他对照debug
     */
    static function error($str, $b=1)
    {       				 
    	if (self::$config['debug'] >= $b)
            echo "\r\n".$str;
        if (self::$config['debug']>1 or !$b)
       		die;
    }
    
    static function autoload($name)
    {
        $a = explode('\\', $name);
        $path = str_replace('\\', DIRECTORY_SEPARATOR, $name);
        
        switch ($a[0]){
            case 'c':
                $file = PROCESSOR_DIR . 'control/'. substr($path, 2) . '.php';
                break;
            case 'm':
                $file = PROCESSOR_DIR . 'model/'. substr($path, 2) . '.php';
                break;
            case 'h':
                $file = PROCESSOR_DIR . 'helper/'.  substr($path, 2) . '.php';
                break;
            default :
                $file = PROCESSOR_DIR . 'lib/'. $path . '.php';
        }          
        
        if (is_file($file))
            require $file;
    }
    
    /**
     *
     * @var int 登录者ID
     */
    static $login_user_id = 0;
    /**
     * 数据操作类
     * @param type $i linkID
     * @return object
     */
    static function get_db_link($i=0)
    {
        $a = require  CONFIG_DIR . 'database.php';
        $con = $a[$i];
        return self::initC('db\\'.$con['type'], $i, $con);
    }
    
    /**
	 * 以某列排序数组
	 * @param type $order
	 * @param type $res
	 * @param type $key
	 * @return type
	 */
	static function arr2_ordering($order, $res, $key='id')
	{
		$res = self::arr2_setKey($res, $key);
		
		$r = array();
        foreach(explode(',', $order) as $id)
            isset($res[$id]) && $r[] = $res[$id]; 
		return $r;
	}
	static function arr2_setKey($res, $key='id')
	{
		$r = array();
		foreach($res as $v)
            $r[$v[$key]] = $v;
		return $r;
	}
	
	/**
     * @var type 存储实例类
     */
    static private $_instance = array();

    /**
     * 实例一个类
     * @param type $c 类名
     * @param string $n  实例别名
     */
    static function initC($c, $n='')
    {
        $n = '___'. $c . $n;
        if (isset(self::$_instance[$n]))
            return self::$_instance[$n];

        // init
        $args = func_get_args();
        switch (func_num_args())
         {
            case 1:
            case 2:
                $init = new $c();
                break;
            case 3:
                $init = new $c($args[2]);
                break;
            case 4:
                $init = new $c($args[2], $args[3]);
                break;
            case 5:
                $init = new $c($args[2], $args[3], $args[4]);
                break;
         }
        self::$_instance[$n] = $init;
        return $init;
    }
    static function callFunction($c, $f)
	{
		if (!method_exists($c, $f))
            YF_f::error(lang::g('function not exist:') . get_class($c) .'->'. $f, 0);
        $args = func_get_args();
        unset($args[0], $args[1]);
		return call_user_func_array(array($c, $f), $args);
	}
    

    /**
     *	创建缓存文件
     *	$c 生成缓存的类
     *	$f 文件名
     *  $b 序列化
     */
	static function cache_file($f, $str)
	{
		if (substr($f, -4)=='.php')
		  {	
            $str = var_export($str, true);
		  	$str = "<?php\nreturn $str;\n?>";
		  }
        if (!self::initC('files')->w_file( CACHE_DIR . $f, $str))
            self::error(lang::g('cache failed:') . $f);
	}

    /**
     *	读取缓存文件
     *	$c 生成缓存的类
     *	$f 文件名
     *  $b 解序列化
     *  $p 生成缓存函数的参数
     */
    static function load_cache($c, $filename='')
    {
		if ($filename==null)
		 {
			$filename = DIRECTORY_SEPARATOR =='/' ? str_replace('\\', DIRECTORY_SEPARATOR, $c) : $c;
			$filename .= '.php';
		 }
		if (!self::is_cache($filename))
		 {
			$c = '\c\\' . $c;
			$C    = self::initC($c);
            $fun  = 'c_caching';
			if (!method_exists($C, $fun))
                self::error( lang::g('function not exist:'). $c . '->' . $fun );
            $args = func_get_args();
			unset($args[0], $args[1]);
			$a = call_user_func_array(array($C, $fun), $args);
            if ($a)
                return $a;
         }          
		return include CACHE_DIR .$filename;
    }
	
    /**
     * 判断缓存文件是否有效
     * 单位为分
     */
	static function is_cache($f)
	{
		$f = CACHE_DIR . $f;
		if (self::$config['cacheTime']>0 && is_file($f))
         {	
            $t = UNIX_TIME - filemtime($f);
			if ($t< self::$config['cacheTime'] * 60)
                return true;
         }		
		return  false;
	}

    
    /**
     * 
     * q_fsockopen
     * @param $url
     * @param $data
     */   
	static function q_fsockopen($url, $data=array())
	{
		$poststr = http_build_query($data);	
		$matches = parse_url($url);
		$host = $matches['host'];	
		$path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';	
		$port = !empty($matches['port']) ? $matches['port'] : 80;
		
		$fp = fsockopen($host, $port, $errno, $errstr, 45);
		if ( !$fp )
			return self::error( 'fsockopen: ' . lang::g('NO') );
		
		$httpHeader  = "POST $path HTTP/1.0\r\n";
		$httpHeader .= "Host: $host\r\n";
		$httpHeader .= "Connection: Close\r\n";
		$httpHeader .= "User-Agent: cHTTP/0.1b (incompatible; M$ sucks; Open Source Rulez)\r\n";
		$httpHeader .= "Content-type: application/x-www-form-urlencoded\r\n";
		$httpHeader .= "Content-length: " . strlen($poststr) . "\r\n";
		$httpHeader .= "\r\n";
		$httpHeader .= $poststr;
		$httpHeader .= "\r\n\r\n";
				
		fwrite($fp, $httpHeader);
		$result = ""; 
		while( !feof($fp))
		   	$result .= fgets($fp, 128);
		fclose($fp);

		$a = explode("\r\n\r\n", $result);
        $res = array($a[0],implode('', $a));
		return $res;
	}
	static function q_curl($url, $data='', $outtime=0, $sendCookie=false)
	{		
	    $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); 
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5); 
        if ($data)
         {
            curl_setopt($ch, CURLOPT_POST, TRUE); 
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
         }
	    if ($outtime)
	    	curl_setopt($ch,CURLOPT_TIMEOUT, $outtime);
        if ($sendCookie)
         {
            $s = $_COOKIE;
            if (strpos($url, ROOT_URL)===0)
                unset($s['PHPSESSID']);
            $s = http_build_query($s, '', '; ');
            curl_setopt($ch, CURLOPT_COOKIE, $s);
            curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
         }
         
	    $ret = curl_exec($ch);
	    if($ret===FALSE)
	    	self::error(curl_error($ch), 2);
	    curl_close($ch);
	    return $ret;
	}
    
    /**
     *  设置 cookie
     * @param string $name
     * @param type $value
     * @param int $days
     * @return boolean
     */
    static function set_cookie($name, $value=null, $days=null)
    {
        $name = self::$config['cookie_pre'].$name;
		$path = self::$config['cookie_path'];
		$domain = self::$config['cookie_domain'];
		
		// de
        if ($days<0)
         {
            if(is_array($_COOKIE[$name]))
             {
                foreach ($_COOKIE[$name] as $key => $value)
                    $b = setcookie($name."[$key]", null, time()-10000);
                return $b;
             }
            return setcookie($name, null, time()-10000, $path, $domain);
         }
		
		// reg
        if ($days)
            $days = time() + 3600 * 24 * $days ;
        $value = encrypt::authcode($value, 0);
        return setcookie($name, $value, $days, $path, $domain);
    }
    static function get_cookie($name)
    {
        $name = self::$config['cookie_pre'] .$name;
        if (!isset($_COOKIE[$name]) )
            return;	
        $value = $_COOKIE[$name];
        return is_array($value) ? array_map(['encrypt','authcode'], $value) : encrypt::authcode($value);  
    }
    
}

spl_autoload_register('YF_f::autoload');
?>